package com.seven.smartsnmp.snmp;

import com.seven.smartsnmp.base.MyException;
import com.seven.smartsnmp.base.SysResource;
import com.seven.smartsnmp.impl.SNMPAPIImpl;
import lombok.extern.slf4j.Slf4j;
import net.percederberg.mibble.MibLoader;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.Serializable;
@Slf4j
public class SNMPFactory implements Serializable {

    //snmpAPi接口
    private volatile static SNMPAPI snmpapi;



    /**
     * 单利模式
     *
     * @return
     * @throws MyException
     */
    public static SNMPAPI getInstance() throws MyException {
        if (snmpapi == null) {
            synchronized (SNMPAPIImpl.class) {
                if (snmpapi == null) {
                    snmpapi = new SNMPAPIImpl();
                }
            }
        }
        return snmpapi;
    }

    /**
     * 初始化加载mib文件
     *
     * @throws MyException
     */
    public static void init() throws MyException {
        try {
            log.info("SNMP网关模块开始初始化！");
            log.info("请确保MIB文件放置在classpath中的mibs包中");
            SysResource.getMibload().addResourceDir("/mibs");
            SysResource.getMibload().load("RFC1213-MIB");
            SysResource.getMibload().load("HOST-RESOURCES-MIB");
            SysResource.getMibload().load("BRIDGE-MIB");
            SysResource.getMibload().load("APPLICATION-MIB");
            log.info("加载默认的RFC1213-MIB、HOST-RESOURCES-MIB、BRIDGE-MIB,APPLICATION-MIB成功！");
            log.info("初始化SNMP模块成功!");
        } catch (Exception e) {
            log.error("初始化SNMP模块出错:," + e.getMessage());
            log.error(e);
            e.printStackTrace();
        }
    }

    /**
     * 动态加载mib文件
     *
     * @param mibFile mib文件在项目中的路径
     * @throws MyException
     */
    public static void loadMib(String mibFile) throws MyException {
        try {
            MibLoader mibLoader = SysResource.getMibload();
            File file = new File(mibFile);
            mibLoader.addDir(file.getParentFile());
            mibLoader.load(file);
            log.info("加载mib文件成功");
        } catch (Exception e) {
            log.info(e.getMessage());
            throw new MyException("加载MIB出错:" + e.getMessage());
        }
    }


    /**
     * 获取snmpapi单例模式
     *
     * @return
     * @throws MyException
     */
    public static SNMPAPI getSNMPAPI() throws MyException {
        getInstance();
        if (snmpapi == null) {
            throw new MyException("SNMPAPI is NULL, Please check call init() first.");
        } else {
            return snmpapi;
        }
    }

}
